package com.carkeeper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carkeeper.mapper.BlogCategoryMapper;
import com.carkeeper.mapper.BlogMapper;
import com.carkeeper.pojo.Blog;
import com.carkeeper.pojo.BlogCategory;
import com.carkeeper.service.BlogCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BlogCategoryServiceImpl extends ServiceImpl<BlogCategoryMapper,BlogCategory> implements BlogCategoryService {

    @Autowired
    private BlogCategoryMapper blogCategoryMapper;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public String addCategory(BlogCategory blogCategory) {
        LambdaQueryWrapper<BlogCategory> blogCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogCategoryLambdaQueryWrapper.eq(BlogCategory::getName, blogCategory.getName());
        BlogCategory blogCategory1 = blogCategoryMapper.selectOne(blogCategoryLambdaQueryWrapper);
        if (null == blogCategory1) {
            blogCategory.setCreateTime(new Date());
            int insert = blogCategoryMapper.insert(blogCategory);
            if (insert > 0) {
                return "新增成功";
            }
        } else {
            return "已存在此分类，不能新增";
        }
        return null;
    }

    @Override
    public String deleteCategory(long id) {

        /*
            方式一：传入参数为实体类属性名
            LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            blogLambdaQueryWrapper.eq(Blog::getBlogCategoryId, id);
        */

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        //参数是数据表的字段名称
        blogQueryWrapper.eq("blog_category_id", id);
        List<Blog> blogList = blogMapper.selectList(blogQueryWrapper);
        if (blogList != null && blogList.size() > 0) {
            return "该分类关联了文章，不能删除";
        }
        int delete = blogCategoryMapper.deleteById(id);
        if (delete > 0) {
            return "删除分类成功";
        }
        return null;
    }

    @Override
    public Boolean updateCategory(BlogCategory blogCategory) {
        int update = blogCategoryMapper.updateById(blogCategory);
        if (update > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<BlogCategory> queryAll() {
        BlogCategory blogCategory = blogCategoryMapper.selectById(1);
        List<BlogCategory> blogCategoryList = blogCategoryMapper.selectList(new QueryWrapper<BlogCategory>());
        return blogCategoryList;
    }


}
